package linhnv.app;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.webkit.URLUtil;
import android.widget.MediaController.MediaPlayerControl;

public class VideoPlayer extends Activity implements OnErrorListener,OnBufferingUpdateListener,
	OnCompletionListener,OnPreparedListener,SurfaceHolder.Callback {

	/**
	 * @param args
	 */
	private MediaPlayer mp;
	private SurfaceView mPreview;
	private SurfaceHolder holder;
	
	private String path="http://daily3gp.com/vids/familyguy_has_own_orbit.3gp";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.surfaceview);
		mPreview= (SurfaceView)findViewById(R.id.surfaceview);
		getWindow().setFormat(PixelFormat.TRANSPARENT);
		
		/*
		 * 
		 */
		holder =mPreview.getHolder();
		holder.addCallback(this);
		holder.setFixedSize(400, 300);
		
		Bundle bundle = getIntent().getExtras();
		// Get the path of bundle
		//path = bundle.getString("url");
		
		playVideo(path);
		
		
	}
	/**
	 * 
	 * @param param
	 */
	private void playVideo(String param){
		
		final String path = param;
		try{
			Log.d("linhnv","==================playVideo+:"+path);
			
			if(mp !=null)
			{
				mp.start();
				return;
			}
			
			mp= new MediaPlayer();
			mp.setOnErrorListener(this);
			mp.setOnBufferingUpdateListener(this);
			mp.setOnPreparedListener(this);
			mp.setOnCompletionListener(this);
			mp.setAudioStreamType(2);
			
			//
			mp.setDisplay(holder);//(SurfaceHolder) mPreview.getHolder().getSurface());
			
			//
			 Runnable r = new Runnable() {

	                public void run() {

	                    try {

	                        setDataSource(path);

	                    } catch (IOException e) {

	                        Log.e("linhnv", e.getMessage(), e);

	                    }

	                    try {
							mp.prepare();
						} catch (IllegalStateException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

	                    Log.d("linhnv", "Duration:  ===>" + mp.getDuration());

	                    mp.start();

	                }

	            };

	            new Thread(r).start();
		}catch( Exception ex)
		{
			if (mp != null) {

                mp.stop();

                mp.release();

            }

			
		}
	}
	
	
/**
 * 
 * @param path
 * @throws IOException
 */
    public void setDataSource(String path) throws IOException {

        if (!URLUtil.isNetworkUrl(path)) {

            mp.setDataSource(path);

        } else {

            URL url = new URL(path);

            URLConnection cn = url.openConnection();

            cn.connect();

            InputStream stream = cn.getInputStream();

            if (stream == null)

                throw new RuntimeException("stream is null");

            File temp = File.createTempFile("mediaplayertmp", "dat");

            String tempPath = temp.getAbsolutePath();

            FileOutputStream out = new FileOutputStream(temp);

            byte buf[] = new byte[128];

            do {

                int numread = stream.read(buf);

                if (numread <= 0)

                    break;

                out.write(buf, 0, numread);

            } while (true);

            mp.setDataSource(tempPath);

            try {

                stream.close();

            }

            catch (IOException ex) {

                Log.e("linhnv", "error: " + ex.getMessage(), ex);

            }

        }

    }

 
	public boolean onError(MediaPlayer mp, int what, int extra) {
		// TODO Auto-generated method stub
		if (mp != null) {

            mp.stop();

            mp.release();

        }
		return false;
	}

	public void onBufferingUpdate(MediaPlayer mp, int percent) {
		// TODO Auto-generated method stub
		Log.d("linhnv","==================onBufferingUpdate");
	}

	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub
		
	}

	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		Log.d("linhnv","==================onPrepared");
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		// TODO Auto-generated method stub
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		// TODO Auto-generated method stub
		
	}

}
